import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Vector;

import edu.stanford.nlp.process.Morphology;

public class DocumentParser {
	
	/**
	 * Return the sentences from the file with ID id that contains the word keyword.
	 * 
	 * The method opens the file based on the ID (all file names are in the form id.txt),
	 * separates the data in sentences and analyze word by word looking for the keyword.
	 * If the keyword is found the sentence which it belongs to is added to the Vector to be returned.
	 * 
	 * @param id		The ID of the document to search for the keyword
	 * @param keyword	Keyword to be searched
	 * @return			A Vector with all the sentences in the document with ID id that contains the keyword
	 */
	public static Vector<String> getSentences(String id, String keyword) {
		Vector<String> sentences = new Vector<String>();
		Morphology morph = new Morphology();

		try {
			FileInputStream fstream = new FileInputStream("CoffeeMachines\\" + id + ".txt");
			
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String line;
			
			while((line = br.readLine()) != null) {
				for(String sentence : line.split("\\.")) {
					for(String word : sentence.split(" ")) {
						if(keyword.equals(morph.stem(word))) // The words in the index are stemed
							sentences.add(sentence);
					}
				}
			}
			
			in.close();
		} catch (Exception e) {
			System.err.println("Error reading file CoffeeMachine\\" + id + ".txt" );
			System.exit(1);
		}
		
		return sentences;
	}
	
	/**
	 * Returns the name of the product related to document with ID id.
	 * 
	 * The method reads the file associated with the ID id and searches for the first line
	 * that starts with the string "Product:". The return value is what appears after.
	 * 
	 * @param id	The ID of the desired document
	 * @return		The name of the product associated with the document
	 */
	public static String getProductName(String id) {
		try {
			FileInputStream fstream = new FileInputStream("CoffeeMachines\\" + id + ".txt");
			
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String line;
			
			while((line = br.readLine()) != null) {
				if (line.startsWith("Product:"))
					return line.split(":")[1].trim();
			}
			
			in.close();
		} catch (Exception e) {
			System.err.println("Error reading file CoffeeMachine\\" + id + ".txt" );
			System.exit(1);
		}
		
		return null;
	}
}
